package top.yxf.spring.beans.factory.support;

import top.yxf.spring.BeansException;
import top.yxf.spring.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;

/**
 * @author xs.wu
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    private InstantiationStrategy instantiationStrategy = new CglibSubclassingInstantiationStrategy();
    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

        Object bean;

        try {
            bean = createBeanInstance(beanName, beanDefinition, args);
        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }
        // 添加到单例
        addSingleton(beanName, beanDefinition);
        return bean;
    }

    public Object createBeanInstance(String beanName,BeanDefinition beanDefinition, Object[] args) {
        Constructor constructor = null;
        Class<?> beanClass = beanDefinition.getBeanClass();
        Constructor<?>[] declaredConstructor = beanClass.getDeclaredConstructors();
        for(Constructor constructor1 : declaredConstructor) {
            if (args != null && constructor1.getParameterTypes().length == args.length) {
                constructor = constructor1;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanDefinition,beanName,constructor,args);
    }

    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
